import axios from 'axios'
import store from 'admin/store'
import {getToken} from 'admin/utils/auth'

const isDev = process.env.NODE_ENV === 'development'
import config from '/config/index'

const service = axios.create({
    // baseURL: isDev ? "http://192.168.2.25:8080" : config.build.env.serviceUrl["admin-api"], // url = base url + request url
    baseURL: '', // url = base url + request url
    // withCredentials: true, // 当跨域请求时发送cookie
    timeout: 1000 * 60, // request timeout
})

service.httpUrl = config.httpUrl //注入

//请求参数
let request_config = {}
// 请求拦截器
service.interceptors.request.use(
    (config) => {
        request_config = config
        // console.log("config", config)
        let option = config.data ? 'data' : 'params'
        //处理数据
        for (let i in config[option]) {
            //去除空格
            if (typeof config[option][i] === 'string') {
                config[option][i] = config[option][i].trim()
            }
            //空值移除
            if (!config[option][i] && config[option][i] !== 0 && typeof config[option][i] !== 'boolean') delete config[option][i]
            // 去除所有$开头字段
            if (/^\$/.test(i)) delete config[option][i]
        }

        // 设置请求头
        if (store.getters.token) {
            config.headers['Authorization'] = getToken()
            config.headers['Content-Type'] = config.headers['Content-Type'] || 'application/json'
        }

        //url为http或者https完整链接路径开头直接请求不拼接baseURL
        if (/(http|https):\/\/([\w.]+\/?)\S*/.test(config.url)) config.baseURL = ''
        if (/\/user-api/.test(config.url)) config.baseURL = '' //登录临时代理
        return config
    },

    (error) => {
        console.log('request-error', error)
        return Promise.reject(error)
    }
)
// 响应拦截器
service.interceptors.response.use(
    (response) => {
        const {apiName, url, params, data} = request_config

        // console.log(apiName, {
        //     '接口地址': url,
        //     '请求参数': params || data,
        //     '响应参数': {...response.data, data: response.data.data }
        // });

        switch (response.data.code) {
            case 200:
                return {...response.data, data: response.data.data}
            case 401: //token失效
                store.dispatch('user/logout', {vm: this})
                window.$app.$notify.warning({
                    title: '暂无权限',
                    message: response.data.msg || '身份认证失败',
                    duration: 5 * 1000,
                })
                return new Object(null)
            case 403: //暂无权限
                window.$app.$notify.warning({
                    title: '暂无权限',
                    message: response.data.msg || '联系管理员添加权限',
                    duration: 5 * 1000,
                })
                return new Object(null)
            case 404: //暂无权限
                window.$app.$notify.warning({
                    title: '404 资源不存在',
                    message: isDev ? '检查接口地址或请求方式是否正确!!!' : response.data.msg,
                    duration: 5 * 1000,
                })
                return new Object(null)
            case 500:
                window.$app.$notify.error({
                    title: '500',
                    message: `服务器错误`,
                    duration: 5 * 1000,
                })
                return new Object(null)
            default:
                window.$app.$notify.error({
                    title: '请求失败',
                    message: response.data.msg || `method=${request_config.method} 请求方式是否正确?`,
                    duration: 5 * 1000,
                })
                return Promise.resolve(response.data.msg || 'Error')
        }
    },
    (error) => {
        console.log('response-error', error) // for debug
        window.$app.$notify.error({
            title: '服务器错误',
            message: error,
            duration: 5 * 1000,
        })

        return Promise.reject(error)
    }
)

// String.prototype.Trim = function () {
//     return this.replace(/(^\s*)|(\s*$)/g, "");
// }

// String.prototype.LTrim = function () {
//     return this.replace(/(^\s*)/g, "");
// }


// String.prototype.RTrim = function () {
//     return this.replace(/(\s*$)/g, "");
// }

export default service
